package service;

import mapper.CpuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import po.ComboboxItem;
import po.Cpu;
import po.Result;

import java.util.ArrayList;
import java.util.List;

@Service
public class CpuServiceImpl implements CpuService {
    @Autowired
    private CpuMapper cpuMapper;

    @Override
    public List<Cpu> findAllCpus(Cpu cpu) throws Exception {
        return cpuMapper.findAllCpus(cpu);
    }

    @Override
    public Result addCpu(Cpu cpu) {
        Result result = new Result();
        try {
            cpuMapper.addCpu(cpu);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("添加失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("添加成功！");
        return result;
    }

    @Override
    public Result deleteCpuById(int id) {
        Result result = new Result();
        try {
            cpuMapper.deleteCpuById(id);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("删除失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("删除成功！");
        return result;
    }

    @Override
    public List<ComboboxItem> findCpuForComb() throws Exception {
        List<Cpu> cpuList = cpuMapper.findAllCpus(null);
        List<ComboboxItem> list = new ArrayList<>();
        for (Cpu cpu : cpuList) {
            ComboboxItem item = new ComboboxItem();
            item.setId(cpu.getId());
            item.setText(cpu.toString());
            list.add(item);
        }
        return list;
    }

    @Override
    public Result updateCpuById(int id, Cpu cpu) {
        Result result = new Result();
        try {
            cpu.setId(id);
            cpuMapper.updateCpuById(cpu);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("修改失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("修改成功！");
        return result;
    }
}
